package com.example.myapplication.ui.calculate;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.myapplication.R;

import java.text.DecimalFormat;


public class CalculateFragment extends Fragment implements View.OnClickListener{

    private TextView tvResult;
    private StringBuilder currentInput = new StringBuilder();
    private double firstValue = 0;
    private String operator = "";
    private boolean isOperatorClicked = false;
    private DecimalFormat decimalFormat = new DecimalFormat("#.########");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_calculate, container, false);

        // 初始化显示
        tvResult = view.findViewById(R.id.tvResult);

        // 绑定按钮点击事件
        bindButtons(view);

        return view;
    }

    private void bindButtons(View view) {
        // 清除类按钮
        view.findViewById(R.id.btnAc).setOnClickListener(this);
        view.findViewById(R.id.btnBackspace).setOnClickListener(this);

        // 数字和小数点
        view.findViewById(R.id.btn0).setOnClickListener(this);
        view.findViewById(R.id.btn00).setOnClickListener(this);
        view.findViewById(R.id.btn1).setOnClickListener(this);
        view.findViewById(R.id.btn2).setOnClickListener(this);
        view.findViewById(R.id.btn3).setOnClickListener(this);
        view.findViewById(R.id.btn4).setOnClickListener(this);
        view.findViewById(R.id.btn5).setOnClickListener(this);
        view.findViewById(R.id.btn6).setOnClickListener(this);
        view.findViewById(R.id.btn7).setOnClickListener(this);
        view.findViewById(R.id.btn8).setOnClickListener(this);
        view.findViewById(R.id.btn9).setOnClickListener(this);
        view.findViewById(R.id.btnDot).setOnClickListener(this);

        // 运算符
        view.findViewById(R.id.btnAdd).setOnClickListener(this);
        view.findViewById(R.id.btnSubtract).setOnClickListener(this);
        view.findViewById(R.id.btnMultiply).setOnClickListener(this);
        view.findViewById(R.id.btnDivide).setOnClickListener(this);
        view.findViewById(R.id.btnPercent).setOnClickListener(this);
        view.findViewById(R.id.btnEqual).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Button btn = (Button) v;
        String text = btn.getText().toString();

        switch (text) {
            // 清除操作
            case "AC":
                clearAll();
                break;
            case "⌫":
                backspace();
                break;

            // 数字和小数点
            case "0":
            case "00":
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
            case ".":
                handleNumberInput(text);
                break;

            // 运算符
            case "+":
            case "−":
            case "×":
            case "÷":
            case "%":
                handleOperator(text);
                break;

            // 等号
            case "=":
                calculateResult();
                break;
        }
    }

    private void handleNumberInput(String input) {
        if (isOperatorClicked) {
            currentInput.setLength(0);
            isOperatorClicked = false;
        }

        // 处理 00 输入
        if (input.equals("00")) {
            if (currentInput.toString().equals("0")) {
                currentInput.setLength(0);
            }
            currentInput.append("00");
        }
        // 处理单个数字
        else {
            // 防止前导零（非小数时）
            if (currentInput.toString().equals("0") && !input.equals(".")) {
                currentInput.setLength(0);
            }
            currentInput.append(input);
        }

        // 限制小数点数量
        if (input.equals(".") && currentInput.toString().contains(".")) {
            currentInput.deleteCharAt(currentInput.length() - 1);
        }

        updateResultDisplay();
    }

    private void handleOperator(String op) {
        if (currentInput.length() == 0) return;

        if (!isOperatorClicked) {
            firstValue = Double.parseDouble(currentInput.toString());
            operator = op;
            isOperatorClicked = true;
            updateResultDisplay(); // 更新显示，可选择显示运算符
        } else {
            // 如果已经点击过运算符，先计算之前的表达式
            calculateResult();
            operator = op;
        }
    }
    private void calculateResult() {
        if (currentInput.length() == 0 || operator.isEmpty()) return;

        double secondValue = Double.parseDouble(currentInput.toString());
        double result = 0;

        switch (operator) {
            case "+":
                result = firstValue + secondValue;
                break;
            case "−":
                result = firstValue - secondValue;
                break;
            case "×":
                result = firstValue * secondValue;
                break;
            case "÷":
                if (secondValue == 0) {
                    tvResult.setText("错误");
                    return;
                }
                result = firstValue / secondValue;
                break;
            case "%":
                result = firstValue * secondValue / 100;
                break;
        }

        // 更新显示
        currentInput.setLength(0);
        currentInput.append(decimalFormat.format(result));
        firstValue = result;
        operator = "";
        isOperatorClicked = true;
        updateResultDisplay();
    }

    private void updateResultDisplay() {
        String displayText = currentInput.toString();

        // 如果是00开头，且长度大于2，移除前导00
        if (displayText.startsWith("00") && displayText.length() > 2) {
            displayText = displayText.substring(2);
        }

        // 如果是0开头，但不是0.，移除前导0
        if (displayText.startsWith("0") && displayText.length() > 1 && !displayText.startsWith("0.")) {
            displayText = displayText.substring(1);
        }

        tvResult.setText(displayText);
    }
    private void clearAll() {
        currentInput.setLength(0);
        firstValue = 0;
        operator = "";
        isOperatorClicked = false;
        tvResult.setText("0");
    }

    private void backspace() {
        if (currentInput.length() > 0) {
            currentInput.deleteCharAt(currentInput.length() - 1);
            if (currentInput.length() == 0) {
                currentInput.append("0");
            }
            updateResultDisplay();
        }
    }
}